{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n",
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'channels_last'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import tensorflow as tf\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "\n",
    "import keras\n",
    "from keras.layers.core import Dense, Flatten\n",
    "from keras.layers.convolutional import Conv2D\n",
    "from keras.layers.pooling import MaxPooling2D\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "\n",
    "K.image_data_format() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-943da1b18fa1>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /Users/cuiyue/Desktop/AI/第六周/mnist/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /Users/cuiyue/Desktop/AI/第六周/mnist/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /Users/cuiyue/Desktop/AI/第六周/mnist/t10k-images-idx3-ubyte.gz\n",
      "Extracting /Users/cuiyue/Desktop/AI/第六周/mnist/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/cuiyue/anaconda3/envs/py27/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: __init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/Users/cuiyue/Desktop/AI/第六周/mnist'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "\n",
    "net = Conv2D(64, kernel_size=[4, 4], strides=[1,1],activation='relu',\n",
    "                 padding='same',input_shape=[28,28,1], kernel_initializer= keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None),\n",
    "             bias_initializer=  keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None))(x_image)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Conv2D(128, kernel_size=[4, 4], strides=[1,1],activation='relu',\n",
    "                padding='same', kernel_initializer= keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None), \n",
    "             bias_initializer=  keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None))(net)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Flatten()(net)\n",
    "net = Dense(2000, activation='relu', kernel_initializer= keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None), \n",
    "            bias_initializer= keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None))(net)\n",
    "net = Dense(10,activation='softmax', kernel_initializer= keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None), \n",
    "            bias_initializer=  keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None))(net)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义动态学习率\n",
    "init_learning_rate = tf.placeholder(tf.float32)\n",
    "epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "current_epoch = global_step//epoch_steps\n",
    "decay_times = current_epoch \n",
    "current_learning_rate = tf.multiply(init_learning_rate, \n",
    "                                    tf.pow(0.575, tf.to_float(decay_times)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.objectives import categorical_crossentropy\n",
    "cross_entropy = tf.reduce_mean(categorical_crossentropy(y_, net))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "\n",
    "train_step = tf.train.GradientDescentOptimizer(current_learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "K.set_session(sess)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 0.523903, l2_loss: 12288.213867, total loss: 1.384079\n",
      "0.91\n",
      "step 200, entropy loss: 0.596091, l2_loss: 12287.519531, total loss: 1.456218\n",
      "0.83\n",
      "step 300, entropy loss: 0.347491, l2_loss: 12286.343750, total loss: 1.207535\n",
      "0.95\n",
      "step 400, entropy loss: 0.191921, l2_loss: 12285.023438, total loss: 1.051872\n",
      "0.95\n",
      "step 500, entropy loss: 0.133618, l2_loss: 12283.667969, total loss: 0.993475\n",
      "0.98\n",
      "step 600, entropy loss: 0.177202, l2_loss: 12282.270508, total loss: 1.036961\n",
      "0.95\n",
      "step 700, entropy loss: 0.113485, l2_loss: 12280.831055, total loss: 0.973143\n",
      "0.99\n",
      "step 800, entropy loss: 0.153801, l2_loss: 12279.405273, total loss: 1.013359\n",
      "0.95\n",
      "step 900, entropy loss: 0.052813, l2_loss: 12277.944336, total loss: 0.912269\n",
      "1.0\n",
      "step 1000, entropy loss: 0.146940, l2_loss: 12276.464844, total loss: 1.006293\n",
      "0.97\n",
      "0.9586\n",
      "step 1100, entropy loss: 0.151878, l2_loss: 12274.969727, total loss: 1.011125\n",
      "0.98\n",
      "step 1200, entropy loss: 0.041367, l2_loss: 12273.504883, total loss: 0.900512\n",
      "1.0\n",
      "step 1300, entropy loss: 0.130705, l2_loss: 12272.010742, total loss: 0.989746\n",
      "0.98\n",
      "step 1400, entropy loss: 0.145203, l2_loss: 12270.517578, total loss: 1.004139\n",
      "0.98\n",
      "step 1500, entropy loss: 0.153846, l2_loss: 12268.981445, total loss: 1.012675\n",
      "0.98\n",
      "step 1600, entropy loss: 0.085029, l2_loss: 12267.492188, total loss: 0.943754\n",
      "0.99\n",
      "step 1700, entropy loss: 0.104557, l2_loss: 12265.948242, total loss: 0.963173\n",
      "1.0\n",
      "step 1800, entropy loss: 0.171715, l2_loss: 12264.438477, total loss: 1.030226\n",
      "0.96\n",
      "step 1900, entropy loss: 0.075895, l2_loss: 12262.889648, total loss: 0.934298\n",
      "1.0\n",
      "step 2000, entropy loss: 0.098639, l2_loss: 12261.345703, total loss: 0.956933\n",
      "1.0\n",
      "0.9775\n",
      "step 2100, entropy loss: 0.099836, l2_loss: 12259.805664, total loss: 0.958022\n",
      "0.99\n",
      "step 2200, entropy loss: 0.110878, l2_loss: 12258.273438, total loss: 0.968957\n",
      "0.97\n",
      "step 2300, entropy loss: 0.085663, l2_loss: 12256.696289, total loss: 0.943632\n",
      "0.98\n",
      "step 2400, entropy loss: 0.086304, l2_loss: 12255.136719, total loss: 0.944164\n",
      "0.99\n",
      "step 2500, entropy loss: 0.059527, l2_loss: 12253.578125, total loss: 0.917278\n",
      "1.0\n",
      "step 2600, entropy loss: 0.028112, l2_loss: 12252.019531, total loss: 0.885753\n",
      "1.0\n",
      "step 2700, entropy loss: 0.106691, l2_loss: 12250.431641, total loss: 0.964221\n",
      "0.99\n",
      "step 2800, entropy loss: 0.051075, l2_loss: 12248.843750, total loss: 0.908494\n",
      "1.0\n",
      "step 2900, entropy loss: 0.081621, l2_loss: 12247.258789, total loss: 0.938929\n",
      "0.99\n",
      "step 3000, entropy loss: 0.028166, l2_loss: 12245.669922, total loss: 0.885363\n",
      "1.0\n",
      "0.9812\n"
     ]
    }
   ],
   "source": [
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "# Train\n",
    "for step in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.01\n",
    "    _, loss, l2_loss_value, total_loss_value,  current_lr_value= sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss, current_learning_rate], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, init_learning_rate:lr})\n",
    "  \n",
    "    if (step+1) % 100 == 0:\n",
    "        print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "        # Test trained model\n",
    "        correct_prediction = tf.equal(tf.argmax(net, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))\n",
    "    if (step+1) % 1000 == 0:\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
